<script setup lang="tsx">
import { nextTick, provide, reactive, ref } from 'vue';
import { Button, Switch } from 'ant-design-vue';
import { changeRoyiRoleStatus, delRoyiRole, exportRoyiRole, getRoyiRoleList } from '@/service/api';
import { parseTime } from '@/utils';
import Modal from '@/components/common/modal.vue';
import { useRouterPush } from '@/hooks/common/router';
import Search from './modules/search.vue';
import AddRoleForm from './modules/add-role-form.vue';
import DataPermissionForm from './modules/data-permission-form.vue';

const { routerPushByKey } = useRouterPush();

const searchParams = ref({
  roleName: null,
  roleKey: null,
  status: null,
  time: null
});
const pagination = reactive({
  current: 1,
  pageSize: 200,
  showSizeChanger: true,
  pageSizeOptions: ['50', '100', '200', '300', '500'],
  showQuickJumper: true,
  showTotal: (total: number) => {
    return `共${total}条`;
  },
  total: 0,
  onChange: async (current: number, size: number) => {
    pagination.current = current;
    pagination.pageSize = size;
    getData();
  }
});

const tableData = ref([]);
const loading = ref(false);
const columnChecks = ref<any[]>([
  {
    key: 'index',
    dataIndex: 'index',
    title: '序号',
    width: 80,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'roleName',
    dataIndex: 'roleName',
    title: '角色名称',
    // width: 150,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'roleKey',
    dataIndex: 'roleKey',
    title: '权限字符',
    // width: 150,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'roleSort',
    dataIndex: 'roleSort',
    title: '显示顺序',
    // width: 100,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'status',
    dataIndex: 'status',
    title: '状态',
    // width: 100,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record, index }) => {
      record.rowStatusChecked = record.status == 0;
      return (
        <Switch
          checked={record.rowStatusChecked}
          onChange={e => {
            window.$modal?.confirm({
              title: `确认要"${e ? '启用' : '停用'}""${record.roleName}"角色吗？`,
              onOk: () => {
                const status = e ? '0' : '1';
                changeRoyiRoleStatus(record.roleId, status).then(({ data, error }) => {
                  if (!error) {
                    window.$message?.success('操作成功');
                    search();
                  }
                });
              },
              onCancel: () => {}
            });
          }}
        ></Switch>
      );
    }
  },
  {
    key: 'createTime',
    dataIndex: 'createTime',
    title: '创建时间',
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      return parseTime(record.createTime);
    }
  },
  {
    key: 'cz',
    dataIndex: 'cz',
    title: '操作',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 300,
    fixed: 'right',
    customRender: ({ record }) => {
      return record.roleId == 1 ? (
        ''
      ) : (
        <div>
          <Button type="primary" ghost size="small" class="m-r8px" onClick={() => handleAdd('edit', record)}>
            编辑
          </Button>
          <Button danger ghost size="small" class="m-r8px" onClick={() => delRole(record.roleId)}>
            删除
          </Button>
          <Button type="primary" ghost size="small" class="m-r8px" onClick={() => dataPermission(record)}>
            数据权限
          </Button>
          <Button
            type="primary"
            ghost
            size="small"
            class="m-r8px"
            onClick={() => {
              assignedUser(record.roleId);
            }}
          >
            分配用户
          </Button>
        </div>
      );
    }
  }
]);
function reset() {
  search();
}

function search() {
  pagination.current = 1;
  getData();
}

function getData() {
  const { time, roleKey, roleName, status } = searchParams.value;
  const params: any = {
    pageNum: pagination.current,
    pageSize: pagination.pageSize,
    roleKey,
    status,
    roleName
  };
  if (time?.[0]) {
    params['params[beginTime]'] = time[0];
    params['params[endTime]'] = time[1];
  }
  loading.value = true;
  // getRoyiRoleList(params).then(({ data, error }) => {
  //   if (!error) {
  //     data.rows.forEach((item, index) => {
  //       item.index = index + 1;
  //     });
  //     pagination.total = data?.total || 0;
  //     tableData.value = data.rows;
  //   }
  // }).finally(() => (loading.value = false));
  getRoyiRoleList(params).then( res => {
    let data = res.otherData
      data.rows.forEach((item, index) => {
        item.index = index + 1;
      });
      pagination.total = data?.total || 0;
      tableData.value = data.rows;
  }).finally(() => (loading.value = false));

}
getData();

const currentRowId = ref(null);
const customRow = record => {
  return {
    style: {
      // 'background-color': record.roleId === currentRowId.value ? 'rgba(86, 205, 243, 0.3)' : ''
      background: record.roleId === currentRowId.value ? '#BAEAFA' : ''
    },
    class: record.roleId === currentRowId.value ? 'jl-table-row-selected' : '',
    onClick: () => {
      currentRowId.value = record.roleId;
    }
  };
};

const selectedRowKeys = ref([]);

function tableSelectChange(val) {
  selectedRowKeys.value = val;
}

const addRolevisible = ref(false);
const addRoleFormRef = ref(null);
const addType = ref('add');

const currentRowData = ref(null);
function handleAdd(type: AntDesign.TableOperateType, rowData = null) {
  addType.value = type;
  currentRowData.value = rowData;
  addRolevisible.value = true;
  nextTick(() => {
    // 添加检查确保 addRoleFormRef 存在且有 getMenuTree 方法再调用
    if (addRoleFormRef.value && typeof addRoleFormRef.value.getMenuTree === 'function') {
      addRoleFormRef.value.getMenuTree();
      console.log(addRoleFormRef.value, 'addRoleFormRef');

      if (type === 'edit') {
        // 添加检查确保 addRoleFormRef 存在且有 getEditData 方法再调用
        if (addRoleFormRef.value && typeof addRoleFormRef.value.getEditData === 'function') {
          addRoleFormRef.value.getEditData(rowData);
        }
      }
    }
  });
}
function handleAddRoleOk() {
  // 添加检查确保 addRoleFormRef 存在且有 submitForm 方法再调用
  if (addRoleFormRef.value && typeof addRoleFormRef.value.submitForm === 'function') {
    addRoleFormRef.value.submitForm();
  }
}

provide('refreshList', (isClose: boolean = true, type) => {
  reset();
  if (isClose) {
    if (type === 1) {
      handleAddClose();
    }
    if (type === 2) {
      handleDateSoreClose();
    }
  }
});
function handleAddClose() {
  // 修复：确保 addRoleFormRef 存在且有 resetForm 方法再调用
  if (addRoleFormRef.value && typeof addRoleFormRef.value.resetForm === 'function') {
    addRoleFormRef.value.resetForm();
  }
  currentRowData.value = null;
  addRolevisible.value = false;
}

function delRole(roleId: string) {
  window.$modal?.confirm({
    title: `是否确认删除角色编号为"${roleId}"的数据项?`,
    onOk: () => {
      delRoyiRole(roleId).then(({ data, error }) => {
        if (!error) {
          window.$message?.success('删除成功!');
          reset();
        } else {
          window.$message?.error('删除失败!');
        }
      });
    },
    onCancel: () => {}
  });
}

function delAll() {
  const roleId = selectedRowKeys.value.join();
  delRole(roleId);
}

const dataPermissionVisible = ref(false);

const currentDataPermissionData = ref(null);
function dataPermission(row) {
  dataPermissionVisible.value = true;
  currentDataPermissionData.value = row;
}

const dataPermissionFormRef = ref(null);
function handleDateSoreOk() {
  dataPermissionFormRef?.value?.submitForm();
}

function handleDateSoreClose() {
  // 修复：确保 dataPermissionFormRef 存在且有 handleDataScopeChange 方法再调用
  if (dataPermissionFormRef.value && typeof dataPermissionFormRef.value.handleDataScopeChange === 'function') {
    dataPermissionFormRef.value.handleDataScopeChange();
  }
}

function assignedUser(id: string) {
  routerPushByKey('manage_role-user', {
    params: {
      id
    }
  });
}

function exportList() {
  const { time, roleKey, roleName, status } = searchParams.value;
  const params: any = {
    pageNum: pagination.current,
    pageSize: pagination.pageSize,
    roleKey,
    status,
    roleName
  };
  if (time?.[0]) {
    params['params[beginTime]'] = time[0];
    params['params[endTime]'] = time[1];
  }
  exportRoyiRole(params);
}
</script>

<template>
  <div class="jl-main-page one-code-ascend min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <Search v-model:model="searchParams" @reset="reset" @search="search" />
    <ACard
      :bordered="false"
      :body-style="{ flex: 1, overflow: 'hidden' }"
      class="table-card flex-col-stretch sm:flex-1-hidden card-wrapper"
    >
      <template #title>
        <AButton type="primary" ghost class="mini-btn mr-8px">
          <template #icon>
            <icon-ic-round-add class="align-sub text-icon" />
          </template>
          <span class="ml-3px" @click="handleAdd('add')">新增</span>
        </AButton>
        <AButton type="primary" ghost class="mini-btn mr-8px" :disabled="selectedRowKeys.length == 0">
          <template #icon>
            <icon-ic-round-add class="align-sub text-icon" />
          </template>
          <span class="ml-3px">编辑</span>
        </AButton>
        <AButton danger ghost class="mini-btn mr-8px" :disabled="selectedRowKeys.length == 0" @click="delAll">
          <template #icon>
            <icon-ic-round-delete class="align-sub text-icon" />
          </template>
          <span class="ml-3px">删除</span>
        </AButton>
        <AButton ghost type="primary" class="mini-btn mr-8px" @click="exportList">
          <template #icon>
            <icon-ic-round-download class="align-sub text-icon" />
          </template>
          <span class="ml-3px">导出</span>
        </AButton>
      </template>
      <template #extra>
        <TableColumnSetting v-model:columns="columnChecks" />
      </template>
      <STable
        :columns="columnChecks"
        :data-source="tableData"
        bordered
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: tableSelectChange }"
        size="small"
        :loading="loading"
        row-key="roleId"
        :pagination="pagination"
        :custom-row="customRow"
        :scroll="{ x: 1680, y: 'auto' }"
        class="h-full"
      />
    </ACard>

    <!-- 新增修改角色对话框 -->
    <Modal
      v-model:visible="addRolevisible"
      :title="addType == 'add' ? '新增' : '修改' + '角色'"
      height="70vh"
      width="800px"
      :destroy-on-close="true"
      @ok="handleAddRoleOk"
      @close="handleAddClose"
    >
      <AddRoleForm ref="addRoleFormRef" :row-data="currentRowData" :operate-type="addType"></AddRoleForm>
    </Modal>

    <Modal
      v-model:visible="dataPermissionVisible"
      title="分配数据权限"
      height="70vh"
      width="800px"
      @ok="handleDateSoreOk"
      @close="handleDateSoreClose"
    >
      <DataPermissionForm ref="dataPermissionFormRef" :row-data="currentDataPermissionData" />
    </Modal>
  </div>
</template>

<style></style>
